﻿namespace Api
{
    [Route("")]
    public class UploadController : AuthBaseController
    {
        #region Ioc
        private readonly IWebHostEnvironment _webHostEnvironment;

        public UploadController(IWebHostEnvironment webHostEnvironment)
        {
            _webHostEnvironment = webHostEnvironment;
        }
        #endregion

        #region Upload
        [Route("upload")]
        [HttpPost]
        [RequestFormLimits(ValueLengthLimit = int.MaxValue, MultipartBodyLengthLimit = long.MaxValue)]
        [RequestSizeLimit(long.MaxValue)]
        public FileModel Upload([FromForm] string dir, [FromForm] IFormFile file)
        {
            //验证文件是否为空
            if (file.IsEmpty())
            {
                throw new CustomException("请上传文件！");
            }

            //验证文件是否有扩展名
            var extName = Path.GetExtension(file.FileName);
            if (extName.IsEmpty())
            {
                throw new CustomException("文件无扩展名信息！");
            }
            extName = extName.ToLower();

            //定义危险文件类型
            List<string> dangerFileExtensions = new List<string>
            {
                ".exe",".bat",".msi",".dll",".com",".reg",".vbs"
            };

            //验证文件类型
            if (dangerFileExtensions.Contains(extName))
            {
                throw new CustomException("上传的文件类型不被允许！");
            }

            //验证文件大小
            if (file.Length > AppSetting.Config.MaxFileSize * 1024 * 1024)
            {
                throw new CustomException("");
            }



            //处理dir的内容，使得dir的值要么是空，要么是前面不能有杠后面必须有/
            if (dir.IsNotEmpty() && dir.StartsWith('/'))
            {
                dir = dir.Substring(1);
            }
            if (dir.IsNotEmpty() && !dir.EndsWith('/'))
            {
                dir += "/";
            }
            dir = dir == "/" ? "" : dir;


            //获取文件夹的物理路径
            string floderPath = Path.Combine(_webHostEnvironment.ContentRootPath, $"Upload/{dir}");
            if (!Directory.Exists(floderPath))
            {
                Directory.CreateDirectory(floderPath);
            }

            //生成一个随机的文件史
            var randFilename = $"{Path.GetFileNameWithoutExtension(file.FileName)}-{DateTime.Now.Ticks}";

            //得到服务器上保存文件的物理地址:   盘符:\文件夹\文件名.扩展名
            var saveFilePath = floderPath + randFilename + extName;

            //把文件保存到服务器
            using (FileStream fs = System.IO.File.Create(saveFilePath))
            {
                file.CopyTo(fs);
                fs.Flush();
            }

            //返回
            return new FileModel
            {
                FileName = Path.GetFileName(file.FileName),
                Url = "/Upload/" + dir + randFilename + extName
            };
        }
        #endregion
    }
}
